﻿namespace ChinaUnicom.Web
{
    using ChinaUnicom.Log;
    using System;
    using System.IO;
    using System.Net;
    using System.Threading;

    static class WebRequestHelper
    {
        public static void Execute(HttpWebRequest request, Action<HttpStatus> callback)
        {
            try
            {
                // Start the asynchronous request.
                request.BeginGetResponse(r =>
                {
                    try
                    {
                        var response = (HttpWebResponse)request.EndGetResponse(r);

                        if (callback != null)
                        {
                            // Read the response into a Stream object.
                            using (Stream responseStream = response.GetResponseStream())
                            {
                                byte[] buffer = new byte[responseStream.Length];
                                responseStream.Read(buffer, 0, buffer.Length);
                                responseStream.Close();

                                HttpStatus status = new HttpStatus(buffer);
                                status.RequestUrl = request.RequestUri.OriginalString;
                                status.StatusCode = response.StatusCode;

                                callback(status);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e);
                    }
                }, null);
            }
            catch (WebException we)
            {
                Logger.Error(we);
                if (callback != null)
                {
                    HttpStatus status = new HttpStatus(null);
                    status.RequestUrl = request.RequestUri.OriginalString;
                    status.Exception = we;

                    callback(status);
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
                if (callback != null)
                {
                    HttpStatus status = new HttpStatus(null);
                    status.RequestUrl = request.RequestUri.OriginalString;
                    status.Exception = e;

                    callback(status);
                }
            }
        }
    }
}
